import { getDefaultState } from './config';
import { INode, State } from './type';
import produce from 'immer';
import { getNodeById } from './utils';

export default produce(function reducer(
  prevState: State = getDefaultState(),
  action: { type: string; payload: any },
) {
  const { type, payload } = action;
  const { nodeList } = prevState;
  switch (type) {
    case 'update': {
      const { id, name } = payload as INode;
      const nodeInfo = getNodeById(id, nodeList);
      if (!nodeInfo) break;
      const { node } = nodeInfo;
      node['name'] = name;
      break;
    }
    case 'add': {
      const { id, name, parentId } = payload as INode & { parentId: string };
      const nodeInfo = getNodeById(parentId, nodeList);
      if (!nodeInfo) break;
      const { node: parentNode } = nodeInfo;
      if (!parentNode.children) {
        parentNode.children = [];
      }
      parentNode.children.push({
        id,
        name,
      });
      break;
    }
    case 'delete': {
      const id = payload as INode['id'];
      const nodeInfo = getNodeById(id, nodeList);
      if (!nodeInfo) break;
      const { node, parent } = nodeInfo;
      const children = parent?.children as INode[];
      // 注意这里需要考虑顶层组件，parent可能为Null
      const index = children.findIndex((item) => item === node);
      children.splice(index, 1);
      break;
    }
    default:
      break;
  }
});
